﻿package com.calefk.modules.math {
	
	public class Vector2D {
		
		public var x:Number;
		public var y:Number;
		
		public function Vector2D(px:Number = 0, py:Number = 0) {
			x = px;
			y = py;
		}
		
		public function add(v:Vector2D):void {
			x += v.x;
			y += v.y;
		}
		
		public function length():Number {
			return Math.sqrt(lengthSQ());
		}
		
		public function lengthSQ():Number { 
			var SQ:Number = (x * x) + (y * y);
			return (SQ);
		}
		
		public function truncate(max:Number):void {
			var len:Number = length();
			if (len > max) {
				// normalize to max
				scale(max / len);
			}
		}
		
		public function scale(s:Number):void {
			x *= s;
			y *= s;
		}
		
		public function normalize(n:Number = 1):void {
			var leng:Number = length();
			if (leng == 0) {
				leng = 1;
			}
			scale(n / leng);
		}
		
		public function getRad():Number {
			return Math.atan2(y , x);
		}
		// Perpendicular horario
		public function getPerp():Vector2D {
			return new Vector2D(-y , x);
		}
		
		public function toZero():void {
			x = 0;
			y = 0;
		}
		
		public function inverse():void {
			x = -x;
			y = -y;
		}
		
		public function setPosition(px:Number , py:Number):void {
			x = px;
			y = py;
		}
		
		public function replaceValuesWith(vector:Vector2D) {
			setPosition(vector.x , vector.y);
		}
		
		public function clone():Vector2D {
			return new Vector2D(x , y);
		}
		
		public function toString():String {
			return "{x:" + x + ",y:" + y + "}";
		}
		
		// static functions
		public static function sum(va:Vector2D , vb:Vector2D):Vector2D {
			var vsum:Vector2D = va.clone();
			vsum.add(vb);
			return vsum;
		}
		
		public static function dotProduct(va:Vector2D , vb:Vector2D):Number {
			return (va.x * vb.x)  + (va.y * vb.y);
		}
		/*
		 * Creara un nuevo vector con la rotacion del vector base
		 * */
				
		public static function rotateNewVector(v:Vector2D , angle:Number):Vector2D {
			var vr:Vector2D = v.clone();
			rotateSameVector(vr , angle);
			return vr;
		}
		
		public static function rotateRevNewVector(v:Vector2D , angle:Number):Vector2D {
			var vr:Vector2D = v.clone();
			rotateRevSameVector(vr , angle);
			return vr;
		}
		/*
		 * Rota el Vector que se envió por parametro
		 * */
		
		public static function rotateSameVector(v:Vector2D, angle:Number):void {
			var cos:Number = Math.cos(angle);
			var sin:Number = Math.sin(angle);
			var x0:Number = (cos * v.x) - (sin * v.y);
			var y0:Number = (cos * v.y) + (sin * v.x);	
			v.x = x0;
			v.y = y0;
		}
		
		public static function rotateRevSameVector(v:Vector2D, angle:Number):void {
			var cos:Number = Math.cos(angle);
			var sin:Number = Math.sin(angle);
			var x0:Number = (cos * v.x) + (sin * v.y);
			var y0:Number = (cos * v.y) - (sin * v.x);			
			v.x = x0;
			v.y = y0;
		}
	}
}